package com.smile.kafka;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.smile.api.FlyApi;
import com.smile.commons.gps.CoordinateTransformUtil;
import com.smile.model.dto.request.*;
import com.smile.model.request.DrcModeEnterRequest;
import com.smile.model.request.FlighttaskUndoRequest;
import com.smile.model.request.LiveStartPushRequest;
import com.smile.model.response.response.GetAirportByIdResponseDTO;
import com.smile.model.response.response.GetAirportInfoResponseDTO;
import com.smile.model.response.response.PayloadDataResponseDTO;
import com.smile.model.response.response.WayPointTaskInfoDTO;
import com.smile.service.AirportInfoService;
import com.smile.service.AirportService;
import com.smile.service.InspectionTaskService;
import com.smile.service.WayPointTaskInfoService;
import com.smile.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Map;

@Component
@Slf4j
public class KafkaConsumer {
    @Autowired
    private AirportService airportService;

    @Resource
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private AirportInfoService airportInfoService;
    @Autowired
    private ApplicationArguments applicationArguments;


    @Autowired
    private DroneService droneService;
    @Autowired
    private FlightLogService flightLogService;

    @Autowired
    private InspectionTaskService inspectionTaskService;

    @Autowired
    private WayPointTaskInfoService wayPointTaskInfoService;
    @Autowired
    FlyApi flyApi;

    @Autowired
    FlightTaskProcessService flightTaskProcessService;

    @Autowired
    MediaService mediaService;

    @Value("${oss.endpoint-media}")
    private String mediaEndpoint;

    @Autowired
    PayloadService payloadService;

//    @KafkaListener(topics = "osd", groupId = "osd-group", autoStartup = "true", concurrency = "3")
    public void osd(ConsumerRecord<String, String> record, @Headers Map<String, Object> headers) {
        String message = record.value();
        try {
            message = message.replace("\\", "");
            String startStr = message.substring(0, 1);
            // 去除开头 " 引号
            if ("\"".equals(startStr)) {
                message = message.substring(1);
            }
            // 去除结尾 " 引号
            String lastStr = message.substring(message.length() - 1, message.length());
            if ("\"".equals(lastStr)) {
                message = message.substring(0, message.length() - 1);
            }
//            System.out.println( message );
            Map<String, Object> map = JSON.parseObject(message, new TypeReference<Map<String, Object>>() {
            });
            String gateway = (String) map.get("gateway");
            String topicSn = (String) map.get("topic_sn");

            long currentTimeMillis = System.currentTimeMillis();
            long timestamp = (Long) map.get("timestamp");

            if ((currentTimeMillis - timestamp) > 10000) {
                System.out.println("时间差:"+(currentTimeMillis - timestamp));
                Date date = new Date(currentTimeMillis);

                // 创建SimpleDateFormat对象并指定格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = sdf.format(date);
                Date date3 = new Date(timestamp);
                String formattedDate2 = sdf.format(date3);

                System.out.println("当前时间: " + formattedDate);
                System.out.println("上传时间: " + formattedDate2);

            } else {
                Map<String, Object> data = (Map<String, Object>) map.get("data");



                //参数中是否有图传连接拓扑

                //判断是机场还是飞行器
                if (!gateway.equals(topicSn) &&  topicSn != null) {
                    System.out.println("gateway:"+gateway);
                    System.out.println("topicSn:"+topicSn);

                    System.out.println("飞行器更新");
                    Boolean isUpdate = false;
                    PayloadDataResponseDTO payloadDataResponseDTO =  payloadService.getPayloadData(gateway);
                    EditDroneRequestDTO editDroneRequestDTO = new EditDroneRequestDTO();
                    editDroneRequestDTO.setDroneSn(payloadDataResponseDTO.getSn());
                    if (data.containsKey("horizontal_speed") ){
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("data", data);
                        map2.put("method", "osd");
                        messagingTemplate.convertAndSend("/topic/" + gateway, JSON.toJSONString(map2));
                        //根据gateway查询对应无人机
                        editDroneRequestDTO.setLongitude((BigDecimal) data.get("longitude"));
                        editDroneRequestDTO.setLatitude((BigDecimal) data.get("latitude"));
                        System.out.println(data.get("attitude_head"));

                        editDroneRequestDTO.setAttitudeHead(  BigDecimal.valueOf(Double.parseDouble(data.get("attitude_head").toString())) );
                        editDroneRequestDTO.setHeight(BigDecimal.valueOf(Double.parseDouble(data.get("height").toString())));
                        isUpdate = true;

                    }

                    if (data.containsKey("firmware_upgrade_status")) {
                        isUpdate = true;

                        editDroneRequestDTO.setFirmwareUpgradeStatus((Integer) data.get("firmware_upgrade_status"));
                    }

                    if (data.containsKey("firmware_version")) {
                        isUpdate = true;
                        editDroneRequestDTO.setFirmwareVersion(data.get("firmware_version").toString());
                    }

                    if (data.containsKey("maintain_status")) {


                        Map<String, Object> maintainStats = (Map<String, Object>) data.get("maintain_status");

                        List<Map<String, Object>> maintain_status_array = (List<Map<String, Object>>) maintainStats.get("maintain_status_array");
                        for (Map<String, Object> map1 : maintain_status_array) {
                            Integer state = (Integer) map1.get("state");
                            //临时更新
                            if (state == 1) {
                                isUpdate = true;
                                editDroneRequestDTO.setMaintainState(state);
                                editDroneRequestDTO.setLastMaintainType((Integer) map1.get("last_maintain_type"));
                                try{
                                    editDroneRequestDTO.setLastMaintainTime((Long) map1.get("last_maintain_time"));
                                }catch (Exception e){
                                    editDroneRequestDTO.setLastMaintainTime(0L);
                                }
                                editDroneRequestDTO.setLastMaintainFlightTime((Long) map1.get("last_maintain_flight_time"));
                                editDroneRequestDTO.setLastMaintainFlightSorties((Integer) map1.get("last_maintain_flight_sorties"));
                            }
                        }
                    }
                    if(isUpdate){
                        droneService.editDrone(editDroneRequestDTO);
                    }
                } else {
                    //是否更新飞行器相关信息
                    Boolean isUpdateDrone = false;
                    EditDroneRequestDTO editDroneRequestDTO = new EditDroneRequestDTO();
                    //机场信息更新
                    EditAirportRequestDTO editAirportRequestDTO = new EditAirportRequestDTO();
                    GetAirportByIdRequestDTO getAirportByIdRequestDTO = new GetAirportByIdRequestDTO();
                    getAirportByIdRequestDTO.setGatewaySn(gateway);
                    GetAirportByIdResponseDTO getAirportByIdResponseDTO = airportService.getAirportByGatewaySn(getAirportByIdRequestDTO);
//                    getAirportByIdResponseDTO.setFlightId(null);
                    //新增机场详情
                    AddAirportInfoRequestDTO addAirportInfoRequestDTO = new AddAirportInfoRequestDTO();
                    EditAirportInfoRequestDTO editAirportInfoRequestDTO = new EditAirportInfoRequestDTO();
                    GetAirportInfoRequestDTO getAirportInfoRequestDTO = new GetAirportInfoRequestDTO();
                    getAirportInfoRequestDTO.setGatewaySn(gateway);
                    GetAirportInfoResponseDTO getAirportInfoResponseDTO = airportInfoService.getAirportInfoByGatewaySn(getAirportInfoRequestDTO);

                    if (getAirportByIdResponseDTO != null) {
                        BeanUtil.copyProperties(getAirportByIdResponseDTO, editAirportRequestDTO);
                        if (getAirportInfoRequestDTO != null) {
                            BeanUtil.copyProperties(getAirportInfoResponseDTO, editAirportInfoRequestDTO);
                        }
                        editAirportInfoRequestDTO.setAirportName(getAirportByIdResponseDTO.getAirportName());
                        editAirportInfoRequestDTO.setOrganizationId(getAirportByIdResponseDTO.getOrganizationId());
//                Boolean result = airportService.addAirport(addAirportRequestDTO);
                        getAirportInfoRequestDTO.setGatewaySn(gateway);
                        addAirportInfoRequestDTO.setGatewaySn(gateway);
                        if (data.containsKey("home_position_is_valid")) {
                            addAirportInfoRequestDTO.setHomePositionIsValid((Integer) data.get("home_position_is_valid"));
                            editAirportInfoRequestDTO.setHomePositionIsValid((Integer) data.get("home_position_is_valid"));
                        }

                        if (data.containsKey("heading")) {
                            addAirportInfoRequestDTO.setHeading(BigDecimal.valueOf(Double.parseDouble(data.get("heading").toString())));
                            editAirportInfoRequestDTO.setHeading(BigDecimal.valueOf(Double.parseDouble(data.get("heading").toString())));
                        }

                        //机场已登记继续下一步
                        if (data.containsKey("wireless_link_topo")) {
                            Map<String, Object> wireless_link_topo = (Map<String, Object>) data.get("wireless_link_topo");
//                            addAirportInfoRequestDTO.setSecretCode((String) wireless_link_topo.get("secret_code"));
                            addAirportInfoRequestDTO.setLeafNodes((String) wireless_link_topo.get("leaf_nodes"));
                            addAirportInfoRequestDTO.setCenterNode((String) wireless_link_topo.get("center_node"));

                            editAirportInfoRequestDTO.setSecretCode((String) wireless_link_topo.get("secret_code"));
                            editAirportInfoRequestDTO.setLeafNodes((String) wireless_link_topo.get("leaf_nodes"));
                            editAirportInfoRequestDTO.setCenterNode((String) wireless_link_topo.get("center_node"));
                        }
                        //机场RTK标定源
                        if (data.containsKey("rtcm_info")) {
                            Map<String, Object> rtcm_info = (Map<String, Object>) data.get("rtcm_info");
                            addAirportInfoRequestDTO.setMountPoint(rtcm_info.get("mount_point").toString());
                            addAirportInfoRequestDTO.setHost(rtcm_info.get("host").toString());
                            addAirportInfoRequestDTO.setRtcmDeviceType((Integer) rtcm_info.get("rtcm_device_type"));
                            addAirportInfoRequestDTO.setSourceType((Integer) rtcm_info.get("source_type"));

                            editAirportInfoRequestDTO.setMountPoint(rtcm_info.get("mount_point").toString());
                            editAirportInfoRequestDTO.setHost(rtcm_info.get("host").toString());
                            editAirportInfoRequestDTO.setRtcmDeviceType((Integer) rtcm_info.get("rtcm_device_type"));
                            editAirportInfoRequestDTO.setSourceType((Integer) rtcm_info.get("source_type"));
                        }
                        //机场空调工作状态信息
                        if (data.containsKey("air_conditioner")) {
                            Map<String, Object> air_conditioner = (Map<String, Object>) data.get("air_conditioner");
                            addAirportInfoRequestDTO.setAirConditionerState((Integer) air_conditioner.get("air_conditioner_state"));
                            editAirportInfoRequestDTO.setAirConditionerState((Integer) air_conditioner.get("air_conditioner_state"));
                        }


                        //机场图传链路
                        if (data.containsKey("wireless_link")) {
                            addAirportInfoRequestDTO.setWirelessLink(data.get("wireless_link").toString());
                            editAirportInfoRequestDTO.setWirelessLink(data.get("wireless_link").toString());
                        }

                        if (data.containsKey("latitude")) {
                            addAirportInfoRequestDTO.setLatitude((BigDecimal) data.get("latitude"));
                            addAirportInfoRequestDTO.setLongitude((BigDecimal) data.get("longitude"));

                            editAirportInfoRequestDTO.setLatitude((BigDecimal) data.get("latitude"));
                            editAirportInfoRequestDTO.setLongitude((BigDecimal) data.get("longitude"));

                            editAirportRequestDTO.setLatitude((BigDecimal) data.get("latitude"));
                            editAirportRequestDTO.setLongitude((BigDecimal) data.get("longitude"));
                        }
                        //风速
                        if (data.containsKey("wind_speed")) {
//                    System.out.println(data.get("wind_speed"));
                            try {
                                addAirportInfoRequestDTO.setWindSpeed((BigDecimal) data.get("wind_speed"));
                                editAirportInfoRequestDTO.setWindSpeed((BigDecimal) data.get("wind_speed"));
                            } catch (Exception e) {

                            }
                        }



                        if (data.containsKey("drone_battery_maintenance_info")) {
                            isUpdateDrone = true;
//                            System.out.println("飞行器电池保养信息");
                            Map<String, Object> droneBatteryMaintenanceInfo = (Map<String, Object>) data.get("drone_battery_maintenance_info");
                            editDroneRequestDTO.setDroneBatteryMaintenanceState((Integer) droneBatteryMaintenanceInfo.get("maintenance_state"));
                            editDroneRequestDTO.setDroneBatteryMaintenanceTimeLeft((Integer) droneBatteryMaintenanceInfo.get("maintenance_time_left"));
                        }

                        if (data.containsKey("maintain_status")) {
//                            System.out.println("机场保养信息保养信息");
//                            System.out.println(data.get("maintain_status"));
                            Map<String, Object> maintainStats = (Map<String, Object>) data.get("maintain_status");

                            List<Map<String, Object>> maintain_status_array = (List<Map<String, Object>>) maintainStats.get("maintain_status_array");
                            for (Map<String, Object> map1 : maintain_status_array) {
                                Integer state = (Integer) map1.get("state");
                                //临时更新
//                                if (state == 1) {
                                    editAirportRequestDTO.setMaintainState(state);
                                    editAirportRequestDTO.setLastMaintainType((Integer) map1.get("last_maintain_type"));
                                    editAirportRequestDTO.setLastMaintainTime(Long.valueOf((Integer) map1.get("last_maintain_time")));
                                    editAirportRequestDTO.setLastMaintainFlightSorties((Integer) map1.get("last_maintain_flight_sorties"));
//                                }
                            }
                        }
                        if (data.containsKey("air_transfer_enable")) {
                            addAirportInfoRequestDTO.setAirTransferEnable((Integer) data.get("air_transfer_enable"));
                            editAirportInfoRequestDTO.setAirTransferEnable((Integer) data.get("air_transfer_enable"));
                        }
                        if (data.containsKey("silent_mode")) {
                            addAirportInfoRequestDTO.setSilentMode((Integer) data.get("silent_mode"));
                            editAirportInfoRequestDTO.setSilentMode((Integer) data.get("silent_mode"));
                        }

                        if (data.containsKey("user_experience_improvement")) {
//                    System.out.println(data.get("user_experience_improvement"));
                            addAirportInfoRequestDTO.setUserExperienceImprovement((Integer) data.get("user_experience_improvement"));
                            editAirportInfoRequestDTO.setUserExperienceImprovement((Integer) data.get("user_experience_improvement"));
                        }

                        if (data.containsKey("maintenance_state")) {
                            addAirportInfoRequestDTO.setMaintenanceState((Integer) data.get("maintenance_state"));
                            editAirportInfoRequestDTO.setMaintenanceState((Integer) data.get("maintenance_state"));
                        }

                        if (data.containsKey("maintenance_time_left")) {
                            addAirportInfoRequestDTO.setMaintenanceTimeLeft((Integer) data.get("maintenance_time_left"));
                            editAirportInfoRequestDTO.setMaintenanceTimeLeft((Integer) data.get("maintenance_time_left"));
                        }

                        if (data.containsKey("heat_state")) {
                            addAirportInfoRequestDTO.setHeatState((Integer) data.get("heat_state"));
                            editAirportInfoRequestDTO.setHeatState((Integer) data.get("heat_state"));
                        }

                        if (data.containsKey("batteries")) {
                            addAirportInfoRequestDTO.setBatteries(data.get("batteries").toString());
                            editAirportInfoRequestDTO.setBatteries(data.get("batteries").toString());
                        }

                        if (data.containsKey("position_state")) {
                            addAirportInfoRequestDTO.setPositionState(data.get("position_state").toString());
                            editAirportInfoRequestDTO.setPositionState(data.get("position_state").toString());
                        }

                        if (data.containsKey("emergency_stop_state")) {
                            addAirportInfoRequestDTO.setEmergencyStopState((Integer) data.get("emergency_stop_state"));
                            editAirportInfoRequestDTO.setEmergencyStopState((Integer) data.get("emergency_stop_state"));
                        }

                        //飞行器电量
                        if (data.containsKey("drone_charge_state")) {
                            Map<String, Object> droneChargeState = (Map<String, Object>) data.get("drone_charge_state");
                            addAirportInfoRequestDTO.setCapacityPercent((Integer) droneChargeState.get("capacity_percent"));
                            editAirportInfoRequestDTO.setCapacityPercent((Integer) droneChargeState.get("capacity_percent"));

                            addAirportInfoRequestDTO.setState((Integer) droneChargeState.get("state"));
                            editAirportInfoRequestDTO.setState((Integer) droneChargeState.get("state"));

                        }
                        if (data.containsKey("sub_device")) {
                            Map<String, Object> subDevice = (Map<String, Object>) data.get("sub_device");
                            try{
                                Integer devicePaired = (Integer) subDevice.get("device_paired");
                                //对频后的无人机再做绑定
                                if(devicePaired == 1){
                                    AddDroneRequestDTO addDroneRequestDTO1 = new AddDroneRequestDTO();
                                    addDroneRequestDTO1.setDroneSn(subDevice.get("device_sn").toString());
                                    if(subDevice.containsKey("device_model_key")){
                                        addDroneRequestDTO1.setDeviceModelKey(subDevice.get("device_model_key").toString());
                                    }
                                    addDroneRequestDTO1.setStatus((Integer) subDevice.get("device_online_status"));
                                    droneService.checkDrone(addDroneRequestDTO1,gateway);
                                }

                            }catch (Exception e){
                                System.out.println(subDevice);
                                System.out.println(e.getMessage());
                            }

                        }
                        if (data.containsKey("state")) {
                            addAirportInfoRequestDTO.setState((Integer) data.get("state"));
                            editAirportInfoRequestDTO.setState((Integer) data.get("state"));
                        }

                        if (data.containsKey("backup_battery")) {
                            addAirportInfoRequestDTO.setBackupBattery(data.get("backup_battery").toString());
                            editAirportInfoRequestDTO.setBackupBattery(data.get("backup_battery").toString());
                        }

                        if (data.containsKey("alarm_state")) {
                            addAirportInfoRequestDTO.setAlarmState((Integer) data.get("alarm_state"));
                            editAirportInfoRequestDTO.setAlarmState((Integer) data.get("alarm_state"));
                        }

                        if (data.containsKey("battery_store_mode")) {
                            addAirportInfoRequestDTO.setBatteryStoreMode((Integer) data.get("battery_store_mode"));
                            editAirportInfoRequestDTO.setBatteryStoreMode((Integer) data.get("battery_store_mode"));
                        }

                        if (data.containsKey("activation_time")) {
                            addAirportInfoRequestDTO.setActivationTime((Integer) data.get("activation_time"));
                            editAirportInfoRequestDTO.setActivationTime((Integer) data.get("activation_time"));
                        }

                        if (data.containsKey("height")) {
                            addAirportInfoRequestDTO.setHeight((BigDecimal) data.get("height"));
                            editAirportInfoRequestDTO.setHeight((BigDecimal) data.get("height"));
                        }

                        if (data.containsKey("alternate_land_point")) {
                            addAirportInfoRequestDTO.setAlternateLandPoint(data.get("alternate_land_point").toString());
                            editAirportInfoRequestDTO.setAlternateLandPoint(data.get("alternate_land_point").toString());
                        }

                        if (data.containsKey("compatible_status")) {
                            addAirportInfoRequestDTO.setCompatibleStatus((Integer) data.get("compatible_status"));
                            editAirportInfoRequestDTO.setCompatibleStatus((Integer) data.get("compatible_status"));
                        }

                        if (data.containsKey("first_power_on")) {
//                    addAirportInfoRequestDTO.setFirstPowerOn((Integer) data.get("first_power_on"));
                        }

                        if (data.containsKey("acc_time")) {
                            addAirportInfoRequestDTO.setAccTime((Integer) data.get("acc_time"));
                            editAirportInfoRequestDTO.setAccTime((Integer) data.get("acc_time"));
                        }

                        if (data.containsKey("storage")) {
                            addAirportInfoRequestDTO.setStorage(data.get("storage").toString());
                            editAirportInfoRequestDTO.setStorage(data.get("storage").toString());
                        }

                        if (data.containsKey("working_current")) {
//                    addAirportInfoRequestDTO.setWorkingCurrent((BigDecimal)data.get("working_current"));
                        }

                        if (data.containsKey("working_voltage")) {
                            addAirportInfoRequestDTO.setWorkingVoltage((Integer) data.get("working_voltage"));
                            editAirportInfoRequestDTO.setWorkingVoltage((Integer) data.get("working_voltage"));
                        }

                        if (data.containsKey("humidity")) {
//                    System.out.println(data.get("humidity"));
                            addAirportInfoRequestDTO.setHumidity((Integer) data.get("humidity"));
                            editAirportInfoRequestDTO.setHumidity((Integer) data.get("humidity"));
                        }

                        if (data.containsKey("temperature")) {
                            try {
                                addAirportInfoRequestDTO.setTemperature((BigDecimal) data.get("temperature"));
                                editAirportInfoRequestDTO.setTemperature((BigDecimal) data.get("temperature"));

                            } catch (Exception e) {
                                addAirportInfoRequestDTO.setTemperature(BigDecimal.valueOf((Integer) data.get("temperature")));
                                editAirportInfoRequestDTO.setTemperature(BigDecimal.valueOf((Integer) data.get("temperature")));
                            }
                        }

                        if (data.containsKey("rainfall")) {
                            try {
                                addAirportInfoRequestDTO.setRainfall((BigDecimal) data.get("rainfall"));
                                editAirportInfoRequestDTO.setRainfall((BigDecimal) data.get("rainfall"));

                            } catch (Exception e) {
                                addAirportInfoRequestDTO.setRainfall(BigDecimal.valueOf((Integer) data.get("rainfall")));
                                editAirportInfoRequestDTO.setRainfall(BigDecimal.valueOf((Integer) data.get("rainfall")));
                            }
                        }


                        if (data.containsKey("environment_temperature")) {
//                    System.out.println(data.get("environment_temperature"));
                            try {
                                addAirportInfoRequestDTO.setEnvironmentTemperature((BigDecimal) data.get("environment_temperature"));
                                editAirportInfoRequestDTO.setEnvironmentTemperature((BigDecimal) data.get("environment_temperature"));
                            } catch (Exception e) {
                                addAirportInfoRequestDTO.setEnvironmentTemperature(BigDecimal.valueOf((Integer) data.get("environment_temperature")));
                                editAirportInfoRequestDTO.setEnvironmentTemperature(BigDecimal.valueOf((Integer) data.get("environment_temperature")));
                            }
                        }

                        if (data.containsKey("job_number")) {
                            addAirportInfoRequestDTO.setJobNumber((Integer) data.get("job_number"));
                            editAirportInfoRequestDTO.setJobNumber((Integer) data.get("job_number"));
                        }

                        if (data.containsKey("drone_in_dock")) {
                            addAirportInfoRequestDTO.setDroneInDock((Integer) data.get("drone_in_dock"));
                            editAirportInfoRequestDTO.setDroneInDock((Integer) data.get("drone_in_dock"));
                        }

                        if (data.containsKey("network_state")) {
                            addAirportInfoRequestDTO.setNetworkState(data.get("network_state").toString());
                            editAirportInfoRequestDTO.setNetworkState(data.get("network_state").toString());
                        }

//                        if (data.containsKey("network_state")) {
//                            addAirportInfoRequestDTO.setNetworkState(data.get("drone_in_dock").toString());
//                            editAirportInfoRequestDTO.setNetworkState(data.get("drone_in_dock").toString());
//                        }

                        if (data.containsKey("supplement_light_state")) {
                            addAirportInfoRequestDTO.setSupplementLightState((Integer) data.get("supplement_light_state"));
                            editAirportInfoRequestDTO.setSupplementLightState((Integer) data.get("supplement_light_state"));
                        }

                        if (data.containsKey("sub_device")) {
                            addAirportInfoRequestDTO.setSubDevice(data.get("sub_device").toString());
                            editAirportInfoRequestDTO.setSubDevice(data.get("sub_device").toString());
                        }

                        if (data.containsKey("flighttask_step_code")) {
                            addAirportInfoRequestDTO.setFlighttaskStepCode((Integer) data.get("flighttask_step_code"));
                            editAirportInfoRequestDTO.setFlighttaskStepCode((Integer) data.get("flighttask_step_code"));
                        }
                        //机场状态{"0":"空闲中","1":"现场调试","2":"远程调试","3":"固件升级中","4":"作业中","5":"待标定"}
                        if (data.containsKey("mode_code")) {
                            addAirportInfoRequestDTO.setModeCode((Integer) data.get("mode_code"));
                            editAirportInfoRequestDTO.setModeCode((Integer) data.get("mode_code"));
                        }

                        if (data.containsKey("firmware_upgrade_status")) {
                            addAirportInfoRequestDTO.setFirmwareUpgradeStatus((Integer) data.get("firmware_upgrade_status"));
                            editAirportInfoRequestDTO.setFirmwareUpgradeStatus((Integer) data.get("firmware_upgrade_status"));
                            editAirportRequestDTO.setFirmwareUpgradeStatus((Integer) data.get("firmware_upgrade_status"));

                        }

                        if (data.containsKey("firmware_version")) {
                            System.out.println(data.get("firmware_version"));
                            addAirportInfoRequestDTO.setFirmwareVersion(data.get("firmware_version").toString());
                            editAirportInfoRequestDTO.setFirmwareVersion(data.get("firmware_version").toString());
                            editAirportRequestDTO.setFirmwareVersion(data.get("firmware_version").toString());
                        }


                        if (Objects.isNull(getAirportInfoResponseDTO)) {
                            airportInfoService.addAirportInfo(addAirportInfoRequestDTO);
                        }

                        if (getAirportInfoResponseDTO != null) {
//                    System.out.println("更新信息");
                            Instant instant = Instant.ofEpochMilli(timestamp);

                            // 将Instant对象转换为LocalDate对象，默认时区为系统时区
                            LocalDateTime localDate = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
                            addAirportInfoRequestDTO.setModifyTime(localDate);
                            airportInfoService.editAirportInfo(editAirportInfoRequestDTO);
                            Map<String, Object> map1 = new HashMap<>();
                            map1.put("data", getAirportInfoResponseDTO);
                            map1.put("method", "info");
                            messagingTemplate.convertAndSend("/topic/" + gateway, JSON.toJSONString(map1));
                        }

                        Boolean result = airportService.editAirport(editAirportRequestDTO);


                        if (isUpdateDrone){
                            PayloadDataResponseDTO payloadDataResponseDTO =  payloadService.getPayloadData(gateway);

                            editDroneRequestDTO.setDroneSn(payloadDataResponseDTO.getSn());
                            droneService.editDrone(editDroneRequestDTO);
                        }
                    }
                }
            }

        } catch (Exception e) {
            System.err.println(e.toString());
            e.printStackTrace();
        }
    }


//    @KafkaListener(topics = "events", groupId = "event-group", autoStartup = "true", concurrency = "3")
    public void event(ConsumerRecord<String, String> record, @Headers Map<String, Object> headers) throws IOException {
        log.info("获取到的信息为：{},", record);

//        System.out.println("发送websocket消息");
        String message = record.value();
//        System.out.println("<UNK>"+message);
//        try {
        message = message.replace("\\", "");
        String startStr = message.substring(0, 1);
        // 去除开头 " 引号
        if ("\"".equals(startStr)) {
            message = message.substring(1);
        }

        // 去除结尾 " 引号
        String lastStr = message.substring(message.length() - 1, message.length());
        if ("\"".equals(lastStr)) {
            message = message.substring(0, message.length() - 1);
        }
//            System.out.println( message );
        Map<String, Object> map = JSON.parseObject(message, new TypeReference<Map<String, Object>>() {
        });
        String gateway = (String) map.get("gateway");
//            messagingTemplate.convertAndSend("/topic/"+gateway, record.value());
        Map<String, Object> data = null;
        try {
            data = (Map<String, Object>) map.get("data");
        } catch (Exception e) {

            System.err.println(message);
        }

        long currentTimeMillis = System.currentTimeMillis();
        long timestamp = (Long) map.get("timestamp");
        String method = (String) map.get("method");
        if ((currentTimeMillis - timestamp) > 30000) {
            System.out.println("大于30s舍弃");
            System.out.println(currentTimeMillis);
            System.out.println(timestamp);
        } else {


            if (!Objects.isNull(method)) {
                //航线管理-返航信息
                if (method.equals("return_home_info")) {
                    messagingTemplate.convertAndSend("/topic/" + gateway, JSON.toJSONString(map));
                }

                if (method.equals("hms")) {

                    List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("list");
//                    System.out.println(list);
                    if (list.size() > 0) {
                        messagingTemplate.convertAndSend("/topic/" + gateway, JSON.toJSONString(map));
                    }
                }
                //航线管理-任务就绪通知
                if (method.equals("flighttask_ready")) {
                    System.out.println("任务就绪通知");


                    List<String> flightIds = JSON.parseObject(data.get("flight_ids").toString(), new TypeReference<List<String>>() {
                    });
                    String flightId = flightIds.get(flightIds.size() - 1);
                    EditAirportRequestDTO editAirportRequestDTO = new EditAirportRequestDTO();
                    try {
                        editAirportRequestDTO.setFlightId(flightId);
                        editAirportRequestDTO.setGateway(gateway);
                        GetAirportByIdRequestDTO getAirportByIdRequestDTO = new GetAirportByIdRequestDTO();
                        getAirportByIdRequestDTO.setGatewaySn(gateway);
                        GetAirportByIdResponseDTO getAirportByIdResponseDTO = airportService.getAirportByGatewaySn(getAirportByIdRequestDTO);
                        editAirportRequestDTO.setId(getAirportByIdResponseDTO.getId());

                        Boolean result = airportService.editAirport(editAirportRequestDTO);
                    } catch (Exception e) {

                    }
                    DrcModeEnterRequest drcModeEnterRequest = new DrcModeEnterRequest();
                    try {
                        System.out.println("任务就绪通知开启drc");
                        drcModeEnterRequest.setEnableTls(false);
                        drcModeEnterRequest.setGateway(gateway);
                        drcModeEnterRequest.setHsiFrequency(1);
                        drcModeEnterRequest.setOsdFrequency(2);
//                        drcModeEnterRequest.setExpireTime(2000L);
                        flyApi.drcModeEnter(drcModeEnterRequest);
                    }catch (Exception e){
                        System.out.println("开启drc失败");
                        System.out.println(e.getMessage());
                    }

                    FlightTaskRequestDTO flightTaskRequestDTO = new FlightTaskRequestDTO();
                    flightTaskRequestDTO.setFlightId(flightId);
                    String fl = flightTaskProcessService.findTask(flightTaskRequestDTO);
                    //查询飞行记录是否存在
                    System.out.println(fl);
                    if (Objects.isNull(fl)) {
                        flightTaskRequestDTO.setFlightId(flightId);
                        flightTaskRequestDTO.setGatewaySn(gateway);
                        flightTaskRequestDTO.setTaskType(1);
                        flightTaskRequestDTO.setStatus(0);
                        flightTaskRequestDTO.setCreateTime(LocalDateTime.now());
                        flightTaskRequestDTO.setModifyTime(LocalDateTime.now());
                        flightTaskRequestDTO.setStartTime(LocalDateTime.now());
                        flightTaskRequestDTO.setDeleteStatus(false);
//                        flightTaskRequestDTO.setOrganizationId(null);
//                        flightTaskRequestDTO.setDroneId(null);
                        flightTaskProcessService.addTask(flightTaskRequestDTO);
                    }

                    GetWayPointTaskInfoByFlightIdRequestDTO getWayPointTaskInfoByFlightIdRequestDTO = new GetWayPointTaskInfoByFlightIdRequestDTO();
                    getWayPointTaskInfoByFlightIdRequestDTO.setFlightId(flightId);
                    getWayPointTaskInfoByFlightIdRequestDTO.setType(0);
                    WayPointTaskInfoDTO wayPointTaskInfoDTO1 = wayPointTaskInfoService.getWayPointTaskInfo(getWayPointTaskInfoByFlightIdRequestDTO);
                    if (Objects.isNull(wayPointTaskInfoDTO1)) {

                        WayPointTaskInfoRequestDTO wayPointTaskInfoRequestDTO = new WayPointTaskInfoRequestDTO();
                        wayPointTaskInfoRequestDTO.setFlightId(flightId);
                        wayPointTaskInfoRequestDTO.setCreateTime(LocalDateTime.now());
                        wayPointTaskInfoRequestDTO.setIndex(0);
                        wayPointTaskInfoRequestDTO.setProcessName("任务就绪");
                        wayPointTaskInfoRequestDTO.setType(0);
                        Integer a = wayPointTaskInfoService.addWayPointTaskInfo(wayPointTaskInfoRequestDTO);

//                        LiveStartPushRequest liveStartPushRequest = new LiveStartPushRequest();
//                        liveStartPushRequest.setGateway(gateway);
//                        liveStartPushRequest.setSn("1581F8HGX252500A0022");
//                        liveStartPushRequest.setType("99-0-0");
//                        liveStartPushRequest.setUrl("rtmp://47.99.37.125:1935/live/8UUXN2800A00HX@1581F8HGX252500A0022");
//                        try {
//                            flyApi.liveStartPush(liveStartPushRequest);
//                        } catch (Exception e) {
//                            //直播开启
//                            System.out.println(e.getMessage());
////                            throw new RuntimeException(e);
//                        }

                        LiveStartPushRequest liveStartPushRequest = new LiveStartPushRequest();

                        PayloadDataResponseDTO payloadDataResponseDTO =  payloadService.getPayloadData(gateway);
                        if (ObjectUtil.isNotNull(payloadDataResponseDTO)) {
                            liveStartPushRequest.setType(payloadDataResponseDTO.getPayloadIndex());
                            String zlmUrl = "rtmp://47.99.37.125:1935/live";
                            liveStartPushRequest.setUrl(zlmUrl+"/"+payloadDataResponseDTO.getGateway()+"@"+payloadDataResponseDTO.getSn());
                            liveStartPushRequest.setGateway(gateway);
                            liveStartPushRequest.setSn(payloadDataResponseDTO.getSn());
                            liveStartPushRequest.setType(payloadDataResponseDTO.getPayloadIndex());
//                            liveStartPushRequest.setUrl("rtmp://47.99.37.125:1935/live/8UUXN2800A00HX@1581F8HGX252500A0022");
                            try {
                                System.out.println("航线准备完成开启直播");
                                System.out.println(liveStartPushRequest.getUrl());
                                flyApi.liveStartPush(liveStartPushRequest);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }

                //航线管理-上报航线任务进度
                if (method.equals("flighttask_progress")) {
//                    System.out.println("上报航线任务进度 发送websocket");
                    messagingTemplate.convertAndSend("/topic/" + gateway, JSON.toJSONString(map));
//                    System.out.println(data);

                    Integer result = (Integer) data.get("result");
                    //更新到数据中
                    Map<String, Object> output = (Map<String, Object>) data.get("output");
                    Map<String, Object> ext = (Map<String, Object>) output.get("ext");
                    Map<String, Object> progress = (Map<String, Object>) output.get("progress");

                    String flightId = (String) ext.get("flight_id");
                    String statusString = (String) output.get("status");

                    Integer currentWaypointIndex = null;
//                        {"canceled":"取消或终止","failed":"失败","in_progress":"执行中","ok":"执行成功","partially_done":"部分完成","paused":"暂停","rejected":"拒绝","sent":"已下发","timeout":"超时"}
                    Integer status;
                    if ("canceled".equals(statusString)) {
                        status = 3;
                    } else if ("failed".equals(statusString)) {
                        status = 5;
                    } else if ("in_progress".equals(statusString)) {
                        status = 2;
                        currentWaypointIndex = (Integer) ext.get("current_waypoint_index");
                        Integer waylineMissionState = (Integer) ext.get("wayline_mission_state");
                        GetWayPointTaskInfoByFlightIdRequestDTO getWayPointTaskInfoByFlightIdRequestDTO = new GetWayPointTaskInfoByFlightIdRequestDTO();
                        Integer index = 0;
                        Integer type = 0;
                        index = currentWaypointIndex;
                        String processName = "";
                        if (waylineMissionState == 2) {
                            getWayPointTaskInfoByFlightIdRequestDTO.setType(2);
                            type = 2;
                            processName = "航线准备";
                            Integer currentStep = (Integer) progress.get("current_step");
                            if (currentStep == 27) {
                                getWayPointTaskInfoByFlightIdRequestDTO.setType(27);
                                type = 27;
                                processName = "飞行器降落机场";
                            }else if (currentStep == 26) {
                                getWayPointTaskInfoByFlightIdRequestDTO.setType(26);
                                type = 26;
                                processName = "开始返航";
                            }
                        } else if (waylineMissionState == 3) {
                            getWayPointTaskInfoByFlightIdRequestDTO.setType(3);
                            type = 3;
                            processName = "航线文件上传";

                            LiveStartPushRequest liveStartPushRequest = new LiveStartPushRequest();

                            PayloadDataResponseDTO payloadDataResponseDTO =  payloadService.getPayloadData(gateway);
                            if (ObjectUtil.isNotNull(payloadDataResponseDTO)) {
                                liveStartPushRequest.setType(payloadDataResponseDTO.getPayloadIndex());
                                String zlmUrl = "rtmp://47.99.37.125:1935/live";
                                liveStartPushRequest.setUrl(zlmUrl+"/"+payloadDataResponseDTO.getGateway()+"@"+payloadDataResponseDTO.getSn());
                                liveStartPushRequest.setGateway(gateway);
                                liveStartPushRequest.setSn(payloadDataResponseDTO.getSn());
                                liveStartPushRequest.setType(payloadDataResponseDTO.getPayloadIndex());
//                            liveStartPushRequest.setUrl("rtmp://47.99.37.125:1935/live/8UUXN2800A00HX@1581F8HGX252500A0022");
                                try {
                                    System.out.println("航线文件上传----->>开启直播");
                                    System.out.println(liveStartPushRequest.getUrl());
                                    flyApi.liveStartPush(liveStartPushRequest);
                                } catch (Exception e) {
                                    throw new RuntimeException(e);
                                }
                            }

                            FlightTaskRequestDTO flightTaskRequestDTO = new FlightTaskRequestDTO();
                            flightTaskRequestDTO.setFlightId(flightId);
                            String fl = flightTaskProcessService.findTask(flightTaskRequestDTO);
                            //查询飞行记录是否存在
                            System.out.println(fl);
                            if (Objects.isNull(fl)) {
                                System.out.println("飞行记录不存在添加");
                                flightTaskRequestDTO.setFlightId(flightId);
                                flightTaskRequestDTO.setGatewaySn(gateway);
                                flightTaskRequestDTO.setTaskType(1);
                                flightTaskRequestDTO.setStatus(0);
                                flightTaskRequestDTO.setCreateTime(LocalDateTime.now());
                                flightTaskRequestDTO.setModifyTime(LocalDateTime.now());
                                flightTaskRequestDTO.setStartTime(LocalDateTime.now());
                                flightTaskRequestDTO.setDeleteStatus(false);
                                flightTaskProcessService.addTask(flightTaskRequestDTO);
                            }

                            EditAirportRequestDTO editAirportRequestDTO = new EditAirportRequestDTO();
                            try {
                                editAirportRequestDTO.setFlightId(flightId);
                                editAirportRequestDTO.setGateway(gateway);
                                GetAirportByIdRequestDTO getAirportByIdRequestDTO = new GetAirportByIdRequestDTO();
                                getAirportByIdRequestDTO.setGatewaySn(gateway);
                                GetAirportByIdResponseDTO getAirportByIdResponseDTO = airportService.getAirportByGatewaySn(getAirportByIdRequestDTO);
                                editAirportRequestDTO.setId(getAirportByIdResponseDTO.getId());

                                Boolean result2 = airportService.editAirport(editAirportRequestDTO);
                            } catch (Exception e) {

                            }
                            DrcModeEnterRequest drcModeEnterRequest = new DrcModeEnterRequest();
                            try {
                                System.out.println("航线上传-开启drc");
                                drcModeEnterRequest.setEnableTls(false);
                                drcModeEnterRequest.setGateway(gateway);
                                drcModeEnterRequest.setHsiFrequency(1);
                                drcModeEnterRequest.setOsdFrequency(2);
//                        drcModeEnterRequest.setExpireTime(2000L);
                                flyApi.drcModeEnter(drcModeEnterRequest);
                            }catch (Exception e){
                                System.out.println("开启drc失败");
                                System.out.println(e.getMessage());
                            }
                        } else if (waylineMissionState == 5) {
                            getWayPointTaskInfoByFlightIdRequestDTO.setType(5);
                            getWayPointTaskInfoByFlightIdRequestDTO.setIndex(index);
                            processName = "到达第一个航点";
                            type = 5;
                        } else if (waylineMissionState == 6) {
                            processName = "到达航点" + currentWaypointIndex;
                            getWayPointTaskInfoByFlightIdRequestDTO.setType(6);
                            getWayPointTaskInfoByFlightIdRequestDTO.setIndex(index);
                            type = 6;

                        } else if (waylineMissionState == 9) {
                            processName = "航线结束";
                            getWayPointTaskInfoByFlightIdRequestDTO.setType(9);
                            getWayPointTaskInfoByFlightIdRequestDTO.setIndex(index);
                            type = 9;
                            FlightTaskRequestDTO flightTaskRequestDTO = new FlightTaskRequestDTO();
                            flightTaskRequestDTO.setFlightId(flightId);
                            System.out.println("航线结束更新");
                            String fl = flightTaskProcessService.findTask(flightTaskRequestDTO);

                            if (ObjectUtil.isNotNull(fl)) {
                                flightTaskRequestDTO.setFlightId(flightId);
                                flightTaskRequestDTO.setStatus(4);
                                flightTaskRequestDTO.setBackTime(LocalDateTime.now());
                                flightTaskProcessService.updateTask(flightTaskRequestDTO);
                            }
                        } else if (waylineMissionState == 8) {
                            processName = "恢复航线";
                            getWayPointTaskInfoByFlightIdRequestDTO.setType(8);
                            getWayPointTaskInfoByFlightIdRequestDTO.setIndex(index);
                            type = 8;
                            index = currentWaypointIndex;
                        } else if (waylineMissionState == 7) {
                            processName = "航线中断";
                            getWayPointTaskInfoByFlightIdRequestDTO.setType(8);
                            getWayPointTaskInfoByFlightIdRequestDTO.setIndex(index);
                            type = 7;

                        }

                        if (!Objects.isNull(getWayPointTaskInfoByFlightIdRequestDTO)) {
                            getWayPointTaskInfoByFlightIdRequestDTO.setFlightId(flightId);
                            WayPointTaskInfoDTO wayPointTaskInfoDTO1 = wayPointTaskInfoService.getWayPointTaskInfo(getWayPointTaskInfoByFlightIdRequestDTO);
                            if (Objects.isNull(wayPointTaskInfoDTO1.getId())) {
                                WayPointTaskInfoRequestDTO wayPointTaskInfoRequestDTO = new WayPointTaskInfoRequestDTO();
                                wayPointTaskInfoRequestDTO.setFlightId(flightId);
                                wayPointTaskInfoRequestDTO.setCreateTime(LocalDateTime.now());
                                wayPointTaskInfoRequestDTO.setIndex(index);
                                wayPointTaskInfoRequestDTO.setProcessName(processName);
                                wayPointTaskInfoRequestDTO.setType(type);
                                Integer a = wayPointTaskInfoService.addWayPointTaskInfo(wayPointTaskInfoRequestDTO);
                            }
                        }
                    } else if ("ok".equals(statusString)) {
                        status = 4;
                        String processName = "任务完成";

                        GetWayPointTaskInfoByFlightIdRequestDTO getWayPointTaskInfoByFlightIdRequestDTO = new GetWayPointTaskInfoByFlightIdRequestDTO();
                        getWayPointTaskInfoByFlightIdRequestDTO.setFlightId(flightId);
                        getWayPointTaskInfoByFlightIdRequestDTO.setType(10);
                        WayPointTaskInfoDTO wayPointTaskInfoDTO1 = wayPointTaskInfoService.getWayPointTaskInfo(getWayPointTaskInfoByFlightIdRequestDTO);
                        if (Objects.isNull(wayPointTaskInfoDTO1.getId())) {
                            WayPointTaskInfoRequestDTO wayPointTaskInfoRequestDTO = new WayPointTaskInfoRequestDTO();
                            wayPointTaskInfoRequestDTO.setFlightId(flightId);
                            wayPointTaskInfoRequestDTO.setCreateTime(LocalDateTime.now());
                            wayPointTaskInfoRequestDTO.setIndex(0);
                            wayPointTaskInfoRequestDTO.setProcessName(processName);
                            wayPointTaskInfoRequestDTO.setType(10);
                            Integer a = wayPointTaskInfoService.addWayPointTaskInfo(wayPointTaskInfoRequestDTO);
                        }

                        FlightTaskRequestDTO flightTaskRequestDTO = new FlightTaskRequestDTO();
                        flightTaskRequestDTO.setFlightId(flightId);
                        String fl = flightTaskProcessService.findTask(flightTaskRequestDTO);
                        if (ObjectUtil.isNotNull(fl)) {
                            flightTaskRequestDTO.setFlightId(flightId);
                            flightTaskRequestDTO.setStatus(4);
                            flightTaskRequestDTO.setEndTime(LocalDateTime.now());
                            flightTaskProcessService.updateTask(flightTaskRequestDTO);
                        }
                    } else if ("partially_done".equals(statusString)) {
                        status = 6;
                    } else {
                        status = 5;
                    }
                    if (status != 3) {
                        inspectionTaskService.editInspectionTaskByFlightId(flightId, result, status, currentWaypointIndex);
                    }
                    if (result != 0 && status != 3) {
                        FlighttaskUndoRequest flighttaskUndoRequest = new FlighttaskUndoRequest();
                        flighttaskUndoRequest.setGateway(gateway);
                        List<String> flightIds = new ArrayList<>();
                        flightIds.add(flightId);
                        flighttaskUndoRequest.setFlightIds(flightIds);
                        try {
                            flyApi.flighttaskUndo(flighttaskUndoRequest);
                        } catch (Exception e) {
                            System.out.println("取消任务失败");
                        }

//                            inspectionTaskService.editInspectionTaskByFlightId(flightId,result,5);
                    }
                }

                //航线管理-设备返航退出状态通知
                if (method.equals("device_exit_homing_notify")) {
                    System.out.println("设备返航退出状态通知");
                    System.out.println(data);
                }


                //航线管理-空中下发航线状态上报
                if (method.equals("in_flight_wayline_progress")) {
                    System.out.println("空中下发航线状态上报");
                    System.out.println(data);
                }

                //飞向目标点事件通知
                if (method.equals("fly_to_point_progress")) {
                    System.out.println("飞向目标点事件通知 发送websocket");
                    System.out.println(map);
                    messagingTemplate.convertAndSend("/topic/" + gateway, JSON.toJSONString(map));
                    System.out.println("飞向目标点事件通知："+data.get("status"));

                }

                //航线管理-空中下发航线状态上报
                if (method.equals("takeoff_to_point_progress")) {
                    System.out.println("一键起飞结果通知 发送websocket");
                    System.out.println(map);
                    messagingTemplate.convertAndSend("/topic/" + gateway, JSON.toJSONString(map));
                    System.out.println("一键起飞进度："+data.get("status"));
                    if (data.get("status").toString().equals("task_ready")) {

                        String flightId = data.get("flight_id").toString();
                        EditAirportRequestDTO editAirportRequestDTO = new EditAirportRequestDTO();
                        editAirportRequestDTO.setFlightId(flightId);
                        editAirportRequestDTO.setGateway(gateway);
                        try {
                            GetAirportByIdRequestDTO getAirportByIdRequestDTO = new GetAirportByIdRequestDTO();
                            getAirportByIdRequestDTO.setGatewaySn(gateway);
                            GetAirportByIdResponseDTO getAirportByIdResponseDTO = airportService.getAirportByGatewaySn(getAirportByIdRequestDTO);
                            editAirportRequestDTO.setId(getAirportByIdResponseDTO.getId());
                            Boolean result = airportService.editAirport(editAirportRequestDTO);
                        } catch (Exception e) {
                            System.out.println("更新flight失败");
                            e.printStackTrace();
                        }
                        System.out.println("一键起飞准备完成 开启直播");
                        LiveStartPushRequest liveStartPushRequest = new LiveStartPushRequest();

                        PayloadDataResponseDTO payloadDataResponseDTO =  payloadService.getPayloadData(gateway);
                        if (ObjectUtil.isNotNull(payloadDataResponseDTO)) {
                            liveStartPushRequest.setType(payloadDataResponseDTO.getPayloadIndex());
                            String zlmUrl = "rtmp://47.99.37.125:1935/live";
                            liveStartPushRequest.setUrl(zlmUrl+"/"+payloadDataResponseDTO.getGateway()+"@"+payloadDataResponseDTO.getSn());
                            liveStartPushRequest.setGateway(gateway);
                            liveStartPushRequest.setSn(payloadDataResponseDTO.getSn());
                            liveStartPushRequest.setType(payloadDataResponseDTO.getPayloadIndex());
//                            liveStartPushRequest.setUrl("rtmp://47.99.37.125:1935/live/8UUXN2800A00HX@1581F8HGX252500A0022");
                            try {
                                flyApi.liveStartPush(liveStartPushRequest);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    } else if (data.get("status").toString().equals("task_finish")) {
                        String flightId = data.get("flight_id").toString();
                        FlightTaskRequestDTO flightTaskRequestDTO = new FlightTaskRequestDTO();
                        flightTaskRequestDTO.setFlightId(flightId);
                        String fl = flightTaskProcessService.findTask(flightTaskRequestDTO);
                        System.out.println("<UNK>" + fl);
                        if (ObjectUtil.isNotNull(fl)) {
                            flightTaskRequestDTO.setFlightId(flightId);
                            flightTaskRequestDTO.setStatus(4);
                            flightTaskRequestDTO.setEndTime(LocalDateTime.now());
                            flightTaskProcessService.updateTask(flightTaskRequestDTO);
                        }
                    }
                }
                //上传拍照进度
                if (method.equals("camera_photo_take_progress")) {
                    System.out.println("发送拍照进度");
                    System.out.println(map);
                    messagingTemplate.convertAndSend("/topic/" + gateway, JSON.toJSONString(map));
                }

                //上传拍照进度
                if (method.equals("file_upload_callback")) {
                    System.out.println("拍照回调");
                    System.out.println(map);
                    AddMediaRequestDTO addMediaRequestDTO = new AddMediaRequestDTO();
//                    data = (Map<String, Object>) map.get("data");
                    Map<String,Object> fileMap =  (Map<String, Object>) data.get("file");
                    Map<String,Object> extMap =  (Map<String, Object>) fileMap.get("ext");
                    Map<String,Object> metadataMap =  (Map<String, Object>) fileMap.get("metadata");
                    String path = fileMap.get("path").toString();
                    addMediaRequestDTO.setDir(path);
                    try{
                        Map<String,Object> positionMap =  (Map<String, Object>) metadataMap.get("shoot_position");
                        addMediaRequestDTO.setLatitude((BigDecimal) positionMap.get("lat"));
                        addMediaRequestDTO.setLongitude((BigDecimal) positionMap.get("lng"));
                    }catch (Exception e){
                        System.out.println("经纬度获取失败");
                    }
                    addMediaRequestDTO.setGateway(gateway);
                    addMediaRequestDTO.setFlightId(extMap.get("flight_id").toString());
                    if (metadataMap.get("absolute_altitude").toString().equals("0")) {
                        addMediaRequestDTO.setAbsoluteAltitude(BigDecimal.valueOf(Double.parseDouble(metadataMap.get("absolute_altitude").toString())));
                        addMediaRequestDTO.setRelativeAltitude(BigDecimal.valueOf(Double.parseDouble(metadataMap.get("relative_altitude").toString())));
                    }else{
                        addMediaRequestDTO.setAbsoluteAltitude((BigDecimal) metadataMap.get("absolute_altitude"));
                        addMediaRequestDTO.setRelativeAltitude((BigDecimal) metadataMap.get("relative_altitude"));
                    }
                    String timeStr =metadataMap.get("created_time").toString();
                    // 解析时间字符串
                    OffsetDateTime odt = OffsetDateTime.parse(timeStr, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
                    // 转换为LocalDateTime
                    LocalDateTime ldt = odt.toLocalDateTime();
                    addMediaRequestDTO.setTakeTime(ldt);
                    addMediaRequestDTO.setDroneModelKey(extMap.get("drone_model_key").toString());
                    addMediaRequestDTO.setPayloadModelKey(extMap.get("payload_model_key").toString());
                    addMediaRequestDTO.setFileName(fileMap.get("name").toString());
                    addMediaRequestDTO.setFileUrl(mediaEndpoint+fileMap.get("object_key").toString());
                    mediaService.addMedia(addMediaRequestDTO);
//                    messagingTemplate.convertAndSend("/topic/" + gateway, JSON.toJSONString(map));
                }
                //飞行详情
                if (method.equals("uom_fly_data_info")) {
                }
            }
        }


    }
//        }catch (Exception e){
//            System.out.println("报错");
//        }


//    @KafkaListener(topics = "state", groupId = "state-group", autoStartup = "true")
    public void state(ConsumerRecord<String, String> record, @Headers Map<String, Object> headers) {
        log.info("获取到的信息为：{},", record);
    }

//    @KafkaListener(topics = "drc_up", groupId = "drc_up_group", autoStartup = "true")
    public void drcUp(ConsumerRecord<String, String> record, @Headers Map<String, Object> headers) {

        String message = record.value();

//        try {
        message = message.replace("\\", "");
        String startStr = message.substring(0, 1);
        // 去除开头 " 引号
        if ("\"".equals(startStr)) {
            message = message.substring(1);
        }

        // 去除结尾 " 引号
        String lastStr = message.substring(message.length() - 1, message.length());
        if ("\"".equals(lastStr)) {
            message = message.substring(0, message.length() - 1);
        }
        Map<String, Object> map = JSON.parseObject(message, new TypeReference<Map<String, Object>>() {
        });
        String gateway = "8UUXN2800A00HX";
        if (map.containsKey("gateway")) {
            gateway = (String) map.get("gateway");
        }

        Map<String, Object> data = (Map<String, Object>) map.get("data");
        long currentTimeMillis = System.currentTimeMillis();
        long timestamp = (Long) map.get("timestamp");

        if ((currentTimeMillis - timestamp) > 5000) {
            System.out.println("延迟高");
        } else {

            String method = (String) map.get("method");

            if (method.equals("osd_info_push")) {
                String topic = "/topic/" + gateway;
                if (data.containsKey("longitude")) {
                    BigDecimal longitude = (BigDecimal) data.get("longitude");
                    BigDecimal latitude = (BigDecimal) data.get("latitude");
                    CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.wgs84ToGcj02(longitude, latitude);
                    data.put("longitude", coordinate.getLongitude());
                    data.put("latitude", coordinate.getLatitude());
                    map.put("data", data);
                    GetAirportByIdRequestDTO getAirportByIdRequestDTO = new GetAirportByIdRequestDTO();
                    getAirportByIdRequestDTO.setGatewaySn(gateway);

                    GetAirportByIdResponseDTO getAirportByIdResponseDTO = airportService.getAirportByGatewaySn(getAirportByIdRequestDTO);
                    messagingTemplate.convertAndSend(topic, JSON.toJSONString(map));
                    FlightLogRequestDTO flightLogRequestDTO = new FlightLogRequestDTO();
                    flightLogRequestDTO.setFlightId(getAirportByIdResponseDTO.getFlightId());
                    flightLogRequestDTO.setAltitude((BigDecimal) data.get("altitude"));
                    flightLogRequestDTO.setHeight((BigDecimal) data.get("height"));
                    flightLogRequestDTO.setLatitude(coordinate.getLatitude());
                    flightLogRequestDTO.setLongitude(coordinate.getLongitude());
                    flightLogRequestDTO.setCreateTime(LocalDateTime.now());
                    flightLogRequestDTO.setGatewaySn(gateway);
//                        flightLogRequestDTO.setGimbalYaw((BigDecimal)  data.get("gimbal_yaw"));
//                        flightLogRequestDTO.setGimbalPitch(Double.parseDouble( data.get("gimbal_pitch").toString()));
//                        flightLogRequestDTO.setGimbalRoll(Double.parseDouble(data.get("gimbal_roll").toString()));
                    flightLogRequestDTO.setSpeedX(Double.parseDouble(data.get("speed_x").toString()));
                    flightLogRequestDTO.setSpeedYy(Double.parseDouble(data.get("speed_y").toString()));
                    flightLogRequestDTO.setSpeedZ(Double.parseDouble(data.get("speed_z").toString()));
                    flightLogRequestDTO.setAttitudeHead(Double.parseDouble(data.get("attitude_head").toString()));
                    flightLogService.addFlightLog(flightLogRequestDTO);

                    try {
                        //根据gateway查询对应无人机
                        PayloadDataResponseDTO payloadDataResponseDTO = payloadService.getPayloadData(gateway);
                        EditDroneRequestDTO editDroneRequestDTO = new EditDroneRequestDTO();
                        editDroneRequestDTO.setDroneSn(payloadDataResponseDTO.getSn());
                        editDroneRequestDTO.setLongitude((BigDecimal) data.get("longitude"));
                        editDroneRequestDTO.setLatitude((BigDecimal) data.get("latitude"));
                        editDroneRequestDTO.setAttitudeHead(BigDecimal.valueOf(Double.parseDouble( data.get("attitude_head").toString())));
                        editDroneRequestDTO.setHeight(BigDecimal.valueOf(Double.parseDouble(data.get("height").toString())));
                        droneService.editDrone(editDroneRequestDTO);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                        System.out.println("高频osd信息更新失败");
                    }
                }

            } else if (method.equals("drc_camera_osd_info_push")) {

                String topic = "/topic/" + gateway;
                messagingTemplate.convertAndSend(topic, JSON.toJSONString(map));
//                    {"data":{"gimbal_pitch":-5.7,"gimbal_roll":0,"gimbal_yaw":-47.780994411692127,"ir_lense":{"ir_fov_info":{"focal_length":40000,"height":4279,"image_ratio":0,"width":5706},"ir_zoom_factor":2,"screen_split_enable":false,"thermal_current_palette_style":6,"thermal_gain_mode":2,"thermal_global_temperature_max":64.878990173339844,"thermal_global_temperature_min":28.7709903717041,"thermal_high_gain_temperature_max":150,"thermal_high_gain_temperature_min":-40,"thermal_isotherm_lower_limit":-20,"thermal_isotherm_state":0,"thermal_isotherm_upper_limit":150,"thermal_low_gain_temperature_max":550,"thermal_low_gain_temperature_min":0},"ir_thermometry":{"ir_metering_mode":0,"ir_metering_point":{"temperature":31.122034072875977,"x":0.5,"y":0.5}},"liveview":{"liveview_world_region":{"bottom":0.53712856769561768,"left":0.45773506164550781,"right":0.547212541103363,"top":0.44965392351150513}},"measure_target":{"measure_target_altitude":27.899999618530273,"measure_target_distance":920.29998779296875,"measure_target_error_state":0,"measure_target_latitude":30.255355011224353,"measure_target_longitude":119.89500438281107},"payload_index":"99-0-0","wide_lense":{"wide_aperture_value":280,"wide_calibrate_farthest_focus_value":133,"wide_calibrate_nearest_focus_value":569,"wide_dewarping_state":0,"wide_exposure_mode":1,"wide_exposure_value":16,"wide_focus_mode":2,"wide_focus_state":0,"wide_focus_value":141,"wide_fov_info":{"focal_length":40000,"height":4279,"image_ratio":0,"width":5706},"wide_iso":150,"wide_max_focus_value":612,"wide_mechanical_shutter_state":0,"wide_min_focus_value":90,"wide_shutter_speed":11},"zoom_lense":{"zoom_aperture_value":280,"zoom_calibrate_farthest_focus_value":133,"zoom_calibrate_nearest_focus_value":569,"zoom_exposure_mode":1,"zoom_exposure_value":16,"zoom_factor":10,"zoom_focus_mode":2,"zoom_focus_state":0,"zoom_focus_value":141,"zoom_fov_info":{"focal_length":40000,"height":4279,"image_ratio":0,"width":5706},"zoom_iso":150,"zoom_max_focus_value":612,"zoom_min_focus_value":90,"zoom_shutter_speed":11}},"method":"drc_camera_osd_info_push","seq":302,"timestamp":1755652965334}

            }else if (method.equals("delay_info_push")) {
//                System.out.println("delay_info_push");
                String topic = "/topic/" + gateway;
                messagingTemplate.convertAndSend(topic, JSON.toJSONString(map));
            }else if (method.equals("hsi_info_push")) {
//                System.out.println("delay_info_push");
                String topic = "/topic/" + gateway;
                messagingTemplate.convertAndSend(topic, JSON.toJSONString(map));
            }
        }
//        }catch (Exception e){
//
//            System.out.println(e.getMessage());
//        }
    }
}
